$(function () {
    // console.log("$out");
    toolBoxMove();
    console.log(localLog("start"));

    $("#clipboard_modal")
        .on("show", function () {
            setKeyboardListening(false);
        })
        .on("hide", function () {
            setKeyboardListening(true);
            checkClipboardTextarea();
        });

    bindTouchModeSwitch();
    $("#clp_save_btn").click(saveInputTextarea);
    $("#osk_btn").click(
        function () {
            if (!G.oskBoard) {
                initOnScreenKeyBoard();
            } else {
                $(".guac-keyboard").toggle();
            }
        }
    );
    $("#tab_btn").click(pressAltTab);
    window.onresize = viewResize;
});

function viewResize() {
    // console.log("resize");
    let width = window.innerWidth;
    if (G.client) {
        G.client.sendSize(width, window.innerHeight);
    }
    if (G.oskBoard) {
        G.oskBoard.resize(width >= 960 ? 960 : width);
    }
}

function pressAltTab() {
    // console.log("TAB_key pressed.");
    let LeftAlt = 65513;
    let Tab = 65289;
    G.client.sendKeyEvent(1, LeftAlt);
    G.client.sendKeyEvent(1, Tab);
    G.client.sendKeyEvent(0, Tab);
    G.client.sendKeyEvent(0, LeftAlt);
}

function initOnScreenKeyBoard() {
    let data = {
        "url": "js/layouts/en-us-qwerty.json",
        "method": "GET",
        "timeout": 0,
    };
    $.ajax(data).done(function (response) {
            // let oskDiv = $("<div id='oskDiv'></div>");
            // oskDiv.setAttribute("id", "oskDiv");
            let oskBoard = new Guacamole.OnScreenKeyboard(new Guacamole.OnScreenKeyboard.Layout(response));
            $("div.ufo").append(oskBoard.getElement());
            oskBoard.resize(window.innerWidth >= 960 ? 960 : window.innerWidth);
            if (G.client) {
                oskBoard.onkeydown = function (keyCode) {
                    G.client.sendKeyEvent(1, keyCode);
                };
                oskBoard.onkeyup = function (keyCode) {
                    G.client.sendKeyEvent(0, keyCode);
                };
            }
            G.oskBoard = oskBoard;
        }
    );
}


function checkClipboardTextarea() {
    let text = $("#clipboardTextarea").val();
    if (text !== clipboardText) {
        // console.log("筐子里和缓存不一样哦");
        // console.log("筐子：" + text);
        // console.log("缓存：" + clipboardText);
        updateClipboardTextarea(clipboardText);
    }
}

let pageTouchMode = true;

function bindTouchModeSwitch() {
    $("#lb1").click(function () {
        if (pageTouchMode !== true) {
            setTouchMode(1);
            pageTouchMode = !pageTouchMode;
        }
    });
    $("#lb2").click(function () {
        if (pageTouchMode !== false) {
            setTouchMode(0);
            pageTouchMode = !pageTouchMode;
        }
    });
}


function toolBoxMove() {
    // ---工具栏拖动---
    //获取元素
    let theUfo = $(".ufo");
    // let dv = theUfo;
    let x = 0;
    let y = 0;
    let l = 0;
    let t = 0;
    let isDown = false;
    //鼠标按下事件
    theUfo.mousedown(function (e) {
        //获取x坐标和y坐标
        x = e.clientX;
        y = e.clientY;
        //获取左部和顶部的偏移量
        l = theUfo.offset().left;
        t = theUfo.offset().top - $(document).scrollTop();
        //开关打开
        isDown = true;
        //设置样式
        theUfo.css("cursor", "move");
    });
    //鼠标移动
    window.onmousemove = function (e) {
        if (isDown === false) {
            return;
        }
        //获取x和y
        let nx = e.clientX;
        let ny = e.clientY;

        //计算移动后的左偏移量和顶部的偏移量
        let nl = nx - (x - l);
        let nt = ny - (y - t);

        theUfo.css("left", nl + 'px');
        theUfo.css("top", nt + 'px');

        if (nt < 0) {
            // console.log("@top");
        }
        if (nl < 0) {
            // console.log("@left");
        }
        if (nl + theUfo.width() > $(window).width()) {
            // console.log("@right");
        }
        // if (nt + theUfo.height() > $(window).height()) { console.log("@DOWN"); }
    };
    // 鼠标抬起事件
    theUfo.mouseup(function (e) {
        //开关关闭
        isDown = false;
        theUfo.css("cursor", "default");
        let gap = 20;
        let nx = e.clientX;
        let ny = e.clientY;
        let nl = nx - (x - l);
        let nt = ny - (y - t);
        // console.log(nl+","+nt+"\nnl+width:"+(nl + theUfo.width())+","+($(window).width()-gap))
        if (nl < gap) {
            // console.info("贴近左边");
        } else {
        }
        if (nt < gap) {
            // console.info("贴近顶边");
        } else {
        }
        if (nl + theUfo.width() > ($(window).width() - gap)) {
            // console.info("贴近右边");
        } else {
        }
    });
    // End of ----工具栏拖动----
}

let log_text = new Date();

function localLog(str) {
    if (str) {
        let now = new Date();
        let m = now.getMonth() < 9 ? "0" + (now.getMonth() + 1) : (now.getMonth() + 1);
        let hour = now.getHours() < 9 ? "0" + now.getHours() : now.getHours();
        let minutes = now.getMinutes() < 9 ? "0" + now.getMinutes() : now.getMinutes();
        let seconds = now.getSeconds() < 9 ? "0" + now.getSeconds() : now.getSeconds();
        let time = now.getFullYear() + "-" + m + "-" + now.getDate() + "\xa0" + hour + ":" + minutes + ":" + seconds;
        let s = time + "|" + str;
        log_text += "\n" + s;
        return s;
    } else {
        return log_text;
    }
}

function notification(str) {
    let delay = 1000;
    UIkit.notification(str, {timeout: delay});
    console.log(localLog(str));
}

function showClientStageNotification(state) {
    let str_client;
    switch (state) {
        case 0:
            str_client = "空闲";
            break;
        case 1:
            str_client = "连接中";
            break;
        case 2:
            str_client = "等待中";
            break;
        case 3:
            str_client = "已连接";
            break;
        case 4:
            str_client = "断开中";
            break;
        case 5:
            str_client = "已断开";
            disconnectUI("[已断开]");
            break;
        default:
            str_client = "default client";
    }
    notification(str_client);
}

function disconnectUI(titleMessage) {
    document.title = titleMessage + document.title;
    $(".ufo").css("opacity", 1);
    $("#shape").css("stroke", "red");
    $("div.goodView>div").css("cursor", "default");
    $("#ufo_nav_icon").text(titleMessage);
}

function showTunnelNotification(state) {
    let str_tunnel;
    switch (state) {
        case 0:
            str_tunnel = "连接中";
            break;
        case 1:
            str_tunnel = "开启";
            break;
        case 2:
            str_tunnel = "关闭";
            disconnectUI("[关闭]");
            break;
        default:
            str_tunnel = "default tunnel";
    }
    notification(str_tunnel);
}

function showErrorNotification(message) {
    notification(message);
}

function updateClipboardTextarea(data) {
    let textarea = $("#clipboardTextarea");
    textarea.val(data);
    clipboardText = data;
    setClipContent(data);
}

let clipboardText = "";

function saveInputTextarea() {
    let text = $("#clipboardTextarea").val();
    if (text !== clipboardText) {
        clipboardText = text;
        writeRemoteClipboard();
    }
    UIkit.modal($("#clipboard_modal")).hide();
}

function writeRemoteClipboard() {
    let writer;
    // Create stream with proper mimetype
    let stream = G.client.createClipboardStream("text/plain");
    // Send data as a string if it is stored as a string
    writer = new Guacamole.StringWriter(stream);
    writer.sendText(clipboardText);
    writer.sendEnd();
}


function waterMark(username) {
    username = !username ? "vesystem" : username;
    for (let i = 0; i <= 5; i++) {
        let shuiyin = document.createElement("div")
        shuiyin.innerText = username + "用户名：123 软件名：123 时间：2020-11-19"
        shuiyin.style.left = (i * 350) + "px"
        shuiyin.style.position = "fixed"
        shuiyin.style.top = (i * 200) + "px"
        shuiyin.style.fontSize = "2vw"
        shuiyin.style.zIndex = "999"
        shuiyin.style.pointerEvents = "none"
        shuiyin.style.color = "#333"
        shuiyin.style.transform = "rotate(-57deg)"
        document.body.append(shuiyin)
    }
}

function getClipContent() {
    navigator.clipboard.readText().then(
        clipText => {
            clipboardText = clipText;
            writeRemoteClipboard();
        }
    );
}

function setClipContent(text) {
    navigator.clipboard.writeText(text)
        .then(() => {
            console.log(localLog('Text copied to clipboard'));
        })
        .catch(err => {
            console.error(localLog('Could not write text'), err);
        });
}